// 封装导出表格
import { saveAs } from 'file-saver'
import request from '@/utils/request'
import qs from 'qs'
// 此函数接受三个参数，请求地址url，接口需要的参数（对象形式），导出的表格名称
function exportexcel (urls, data, name) {
  // 发起请求
  request.post(urls, qs.stringify(data), { isParams: true, responseType: 'arraybuffer' }).then(res => {
    // 拿到res转blob
    const blobContent = new Blob([res])
    // blob转地址
    const url = window.URL.createObjectURL(blobContent)
    // 开始导出
    saveAs(url, `${name}.xls`)
  })
}
// 文件下载
function downloadFile (fileName, base64Data) {
  const byteCharacters = atob(base64Data)
  const byteNumbers = new Array(byteCharacters.length)
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i)
  }
  const byteArray = new Uint8Array(byteNumbers)
  const blob = new Blob([byteArray], { type: 'application/octet-stream' })

  const url = URL.createObjectURL(blob)

  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = url
  a.download = fileName

  document.body.appendChild(a)
  a.click()

  URL.revokeObjectURL(url)
  document.body.removeChild(a)
}
export { exportexcel, downloadFile }